package com.xiaoshuidi.cloud.module.iot.mq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.contract.vo.CustomerInfoVO;
import com.xiaoshuidi.cloud.module.contract.vo.RenterVO1;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.ammeter.AmmeterSwitchOnOffReqVO;
import com.xiaoshuidi.cloud.module.iot.dal.model.ammeter.AmmeterSwitchOnOffResVO;
import com.xiaoshuidi.cloud.module.iot.dal.model.watermeter.WaterMeterSwitchOnOffReqVO;
import com.xiaoshuidi.cloud.module.iot.dal.model.watermeter.WaterMeterSwitchOnOffResVO;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.iot.service.AmmeterService;
import com.xiaoshuidi.cloud.module.iot.service.InteceptorService;
import com.xiaoshuidi.cloud.module.iot.service.WaterMeterService;
import com.xiaoshuidi.cloud.module.iot.service.impl.LocalCallbackServiceImpl;
import com.xiaoshuidi.cloud.module.rooms.api.sdiot.IotRoomDeviceApi;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomSdiotDeviceMappingVo;
import com.xiaoshuidi.cloud.module.system.api.sms.SmsSendApi;
import com.xiaoshuidi.cloud.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


/**
 * @BelongsProject: lease-module-new-iot
 * @BelongsPackage: com.xiaoshuidi.cloud.module.iot.mq
 * @Author: James
 * @CreateTime: 2023-06-20  15:11
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component("IotConsumer")
public class IotConsumer implements Consumer<String> {
    @Autowired
    LocalCallbackServiceImpl localCallbackService;
    @Autowired
    IotRoomDeviceApi iotRoomDeviceApi;
    @Autowired
    AmmeterService ammeterService;

    @Autowired
    WaterMeterService waterMeterService;
    @Autowired
    private InteceptorService inteceptorService;
    @Resource
    private SmsSendApi smsFeignService;

    @Resource
    private ContractApi contractApi;


    @Override
    public void accept(String s) {
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray jsonArray = jsonObject.getJSONArray("roomIds");
        log.info("消费者-IotConsumer: message = " + s);
        TenantUtils.execute(jsonObject.getLong("tenantId"), () -> {
            for (int i = 0; i < jsonArray.size(); i++) {
                //根据房源id查询设备,并根据钱包余额判断是否断电
                ResultModel<List<RoomSdiotDeviceMappingVo>> deviceInfoByRoomId = iotRoomDeviceApi.getDeviceInfoByRoomId(jsonArray.getLong(i));
                log.info("根据房源id查询设备：" + JSONObject.toJSONString(deviceInfoByRoomId));
                BigDecimal account = new BigDecimal(jsonObject.getString("balance"));
                List<RoomSdiotDeviceMappingVo> data = deviceInfoByRoomId.getData();
                if (CollectionUtil.isNotEmpty(data)) {
                    if (account.compareTo(BigDecimal.ZERO) < 0) {
                        RoomSdiotDeviceMappingVo roomSdiotDeviceMappingVo = data.get(0);
                        //当欠费小于0时 发送短信提醒
                        sendMessage(roomSdiotDeviceMappingVo.getRoomHouseId());
                    }
                }
                for (RoomSdiotDeviceMappingVo roomSdiotDeviceMappingVo : data) {
                    if (account.compareTo(BigDecimal.ZERO) < 0) {
                        if (DeviceTypeEnum.AMMETER.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType())) {
                            TbDeviceDo tbDeviceDo = new TbDeviceDo();
                            tbDeviceDo.setDeviceNo(roomSdiotDeviceMappingVo.getDeviceNo());
                            tbDeviceDo.setDeviceType(DeviceTypeEnum.AMMETER.getCode());
                            localCallbackService.disposePrepaymentLogic(tbDeviceDo, account);
                            //添加操作记录：跳闸
                            inteceptorService.addOperateRecord(roomSdiotDeviceMappingVo.getDeviceNo(), 10);
                        } else if (DeviceTypeEnum.COLD_WATERMETE_TYPE_ENUM.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType())) {
                            TbDeviceDo tbDeviceDo = new TbDeviceDo();
                            tbDeviceDo.setDeviceNo(roomSdiotDeviceMappingVo.getDeviceNo());
                            tbDeviceDo.setDeviceType(DeviceTypeEnum.COLD_WATERMETE_TYPE_ENUM.getCode());
                            localCallbackService.disposePrepaymentLogic(tbDeviceDo, account);
                            //添加操作记录： 冷水断水
                            inteceptorService.addOperateRecord(roomSdiotDeviceMappingVo.getDeviceNo(), 10);
                        } else if (DeviceTypeEnum.HOT_WATERMETE_TYPE_ENUM.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType())) {
                            TbDeviceDo tbDeviceDo = new TbDeviceDo();
                            tbDeviceDo.setDeviceNo(roomSdiotDeviceMappingVo.getDeviceNo());
                            tbDeviceDo.setDeviceType(DeviceTypeEnum.HOT_WATERMETE_TYPE_ENUM.getCode());
                            localCallbackService.disposePrepaymentLogic(tbDeviceDo, account);
                            //添加操作记录：热水断水
                            inteceptorService.addOperateRecord(roomSdiotDeviceMappingVo.getDeviceNo(), 10);
                        }
                    } else {
                        if (DeviceTypeEnum.AMMETER.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType())) {
                            AmmeterSwitchOnOffReqVO ammeterSwitchOnOffReqVO = new AmmeterSwitchOnOffReqVO();
                            ammeterSwitchOnOffReqVO.setDeviceNo(roomSdiotDeviceMappingVo.getDeviceNo());
                            TbDeviceDo tbDeviceDo = new TbDeviceDo();
                            ammeterSwitchOnOffReqVO.setTbDeviceDo(tbDeviceDo);
                            try {
                                ResultModel<AmmeterSwitchOnOffResVO> ammeterSwitchOnOffResVOResultModel = ammeterService.setAmmeterSwitchOn(ammeterSwitchOnOffReqVO);
                                log.info("电表合闸操作结果：" + JSONObject.toJSONString(ammeterSwitchOnOffResVOResultModel));
                                //添加操作记录：合闸
                                inteceptorService.addOperateRecord(roomSdiotDeviceMappingVo.getDeviceNo(), 9);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if (DeviceTypeEnum.COLD_WATERMETE_TYPE_ENUM.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType()) || DeviceTypeEnum.HOT_WATERMETE_TYPE_ENUM.getCode().equals(roomSdiotDeviceMappingVo.getDeviceType())) {
                            WaterMeterSwitchOnOffReqVO waterMeterSwitchOnOffReqVO = new WaterMeterSwitchOnOffReqVO();
                            waterMeterSwitchOnOffReqVO.setDeviceNo(roomSdiotDeviceMappingVo.getDeviceNo());
                            TbDeviceDo tbDeviceDo = new TbDeviceDo();
                            waterMeterSwitchOnOffReqVO.setTbDeviceDo(tbDeviceDo);
                            try {
                                ResultModel<WaterMeterSwitchOnOffResVO> waterMeterSwitchOnOffResVOResultModel = waterMeterService.setWaterMeterSwitchOn(waterMeterSwitchOnOffReqVO);
                                log.info("冷热水表供水操作结果：" + JSONObject.toJSONString(waterMeterSwitchOnOffResVOResultModel));
                                //添加操作记录：冷热水表供水
                                inteceptorService.addOperateRecord(roomSdiotDeviceMappingVo.getDeviceNo(), 9);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                    }
                }
            }
        });
    }

    public void sendMessage(Long roomId) {
        try {
            CommonResult<RenterVO1> contractRenterInfoByRoomId = contractApi.getContractRenterListByRoomId(roomId);
            log.info("欠费发送短信，合同信息： {}", JsonUtils.toJsonString(contractRenterInfoByRoomId));
            RenterVO1 renterVO = contractRenterInfoByRoomId.getData();
            List<CustomerInfoVO> custmerInfoList = renterVO.getCustmerInfoList();
            for (CustomerInfoVO customerInfoVO : custmerInfoList) {
                if(ObjectUtil.isNotEmpty(customerInfoVO)){
                    String customerPhone = customerInfoVO.getCustomerPhone();
                    SmsSendSingleToUserReqDTO dto = new SmsSendSingleToUserReqDTO();
                    Map<String, Object> templateParams = Maps.newHashMap();
                    dto.setTemplateParams(templateParams);
                    dto.setTemplateCode("user-sms-balance");
                    dto.setMobile(customerPhone);
                    log.info("当欠费小于0时 发送短信提醒##################" + JSONObject.toJSONString(dto));
                    CommonResult<Long> longCommonResult = smsFeignService.sendSingleSmsToMember(dto);
                    log.info("当欠费小于0时 发送短信提醒##################结果" + JSONObject.toJSONString(longCommonResult));
                }

            }

        } catch (Exception e) {
            log.error("短信发送失败：", e);
        }

    }


}
